package org.mobile.model.util;

import java.util.Iterator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.xml.XMLSerializer;

public class XMLToJSONUtils {
	
	/**
	 * 获取xml中所有的节点，递归实现
	 * 
	 * @param <Element>
	 * @return JSONObject
	 */

	@SuppressWarnings("rawtypes")
	public static JSONObject getAllNode(Element rootElm) {
		JSONObject jobj = new JSONObject();
		for (Iterator i = rootElm.elementIterator(); i.hasNext();) {
			Element element = (Element) i.next();

			if (element.getName().equals("array")) {
				String childName = element.attributeValue("name");
				JSONArray arr = new JSONArray();
				for (Iterator n = element.elementIterator(); n.hasNext();) {
					JSONObject temp = new JSONObject();
					Element el = (Element) n.next();
					if (el.elementIterator().hasNext()) {
						if (el.getName().equals("array"))
						{
							JSONArray arrList = new JSONArray();
							arrList.add(getAllNode(el));
							temp.put(el.attributeValue("name"),arrList);
						}
						else
						{
							temp.put(el.attributeValue("name"),getAllNode(el));
						}
					} else {
						temp.put(el.attributeValue("name"),
								el.attributeValue("type"));
					}

					arr.add(temp);
				}
				jobj.put(childName, arr);
				
			} else if (element.getName().equals("object")) {
				String objectName = element.attributeValue("name");
				JSONObject tempObj = new JSONObject();
				for (Iterator n = element.elementIterator(); n.hasNext();) {
					Element el = (Element) n.next();
					if (el.elementIterator().hasNext()) {
						if (el.getName().equals("array"))
						{
							JSONArray arrList = new JSONArray();
							arrList.add(getAllNode(el));
							tempObj.put(el.attributeValue("name"),arrList);
						}
						else
						{
							tempObj.put(el.attributeValue("name"),getAllNode(el));
						}
					} else {
						tempObj.put(el.attributeValue("name"),el.attributeValue("type"));
					}

				}
				jobj.put(objectName, tempObj);
			} else {
				jobj.put(element.attributeValue("name"),
						element.attributeValue("type"));
			}
		}

		return jobj;
	}

	/**
	 * 将XML转换成JSONObject对象
	 * @param json
	 * @return
	 */
	public static JSONObject ConvertJSONtoXML(Document document,String rootKey) throws DocumentException {
		Element rootElm = document.getRootElement();
		Element root1Elm = rootElm.element(rootKey);
		JSONObject jobj = new JSONObject();
		jobj = getAllNode(root1Elm);

		System.out.println("转换结果：" + jobj);
		return jobj;
	}
	
	/**
	 * 将JSONObject转换成xml
	 * @param json
	 * @return
	 */
    public static String ConvertXMLtoJSON(String json)  {  
    	JSONObject jobj = JSONObject.fromObject(json);
        String xml =  new XMLSerializer().write(jobj);
        System.out.println("转换结果：" + xml);
        return xml;
    } 
}
